//
//  RadioListViewController.m
//  CatMusic
//
//  Created by dllo on 15/4/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RadioListViewController.h"
#import "MVListCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "RadioTracksViewController.h"
#import "NightMode.h"
#import "AFNetworkReachabilityManager.h"
#import "MJRefresh.h"
#import "NetWorkingTool.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface RadioListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, retain)UICollectionView *radioCV;
@end

@implementation RadioListViewController

- (void)dealloc
{
    [_radioCV release];
    [_arr release];
    [super dealloc];
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"电台";
    
    // 夜间模式判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLightDayModel) name:@"LightDayNSNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNightDayModel) name:@"NightDayNSNotification" object:nil];
    
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }

    
    
    UICollectionViewFlowLayout *radioFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    radioFlowLayout.itemSize = CGSizeMake(WIDTH / 375 * 160,200);
    radioFlowLayout.minimumInteritemSpacing = 10;
    radioFlowLayout.minimumLineSpacing = 5;
    radioFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
   self.radioCV = [[UICollectionView alloc] initWithFrame:CGRectMake(WIDTH / 375 * 10, 20, self.view.frame.size.width - 20, self.view.frame.size.height - 100) collectionViewLayout:radioFlowLayout];
    
    self.radioCV.backgroundColor = [UIColor whiteColor];
    self.radioCV.delegate = self;
    self.radioCV.dataSource = self;
    [self.view addSubview:self.radioCV];
    [self.radioCV registerClass:[MVListCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    self.radioCV.backgroundColor = [UIColor clearColor];
    
    
    
    
#pragma mark - 判断网络状态    AFN
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                [self alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                [self creatDataRadio];
                [self radioCVRefresh];
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
  
}


// 电台解析数据
- (void)creatDataRadio
{
    [NetWorkingTool netWorkingToolStr:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=all&condition=hot&device=iPhone&page=1&per_page=200&status=0&tag_name=" block:^(id result) {
        NSMutableDictionary *dic = result;
        self.arr = [dic objectForKey:@"list"];
        [self.radioCV reloadData];
    }];
}



// 下拉刷新
- (void)radioCVRefresh
{
    [self.radioCV addLegendHeaderWithRefreshingBlock:^{
        // 延迟加载数据，2秒后才调用
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.radioCV reloadData];
            
            // 结束刷新
            [self.radioCV.header endRefreshing];
        });
        
    }];
}


- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}

- (void)alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机自带网络" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}




-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    MVListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    NSString *str = self.arr[indexPath.row][@"albumCoverUrl290"];
    NSURL *url = [NSURL URLWithString:str];
    [cell.baseImageViewCollection sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeHolder"]];
    cell.baseTitleCollection.text = self.arr[indexPath.row][@"title"];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *idNum = self.arr[indexPath.row][@"id"];
    NSString *urlHead = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@", idNum];
    NSString *url = [NSString stringWithFormat:@"%@/true/1/30?device=iPhone", urlHead];
    RadioTracksViewController *radioTracksVC = [[RadioTracksViewController alloc] init];
    radioTracksVC.url = url;
    [self.navigationController pushViewController:radioTracksVC animated:YES];
    [radioTracksVC release];
}



- (void)setLightDayModel
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////

    
    UIColor * color = [UIColor blackColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    
}

- (void)setNightDayModel
{
    self.view.backgroundColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    
    UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;

    
    
}












- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
